import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
// import { useStore } from "@/store/index";

export default class ApiService {
	private axiosInstance: AxiosInstance;

	constructor(baseURL?: string, headers: any = {}) {
		this.axiosInstance = axios.create({ baseURL: baseURL, headers });

		// 添加请求拦截器
		this.axiosInstance.interceptors.request.use(
			(config) => {
				// config.headers.Authorization = useStore().getToken;
				return config;
			},
			(error: any) => {
				// 对请求错误做些什么
				return Promise.reject(error);
			}
		);
		// 添加响应拦截器
		this.axiosInstance.interceptors.response.use(
			(response: AxiosResponse<any>) => {
				// 对响应数据做点什么
				return response;
			},
			(error: any) => {
				// 对响应错误做点什么
				return Promise.reject(error);
			}
		);
	}

	// static

	public async get<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
		const res = await this.axiosInstance.get(url, { params, ...config });
		return res.data;
	}

	public async post<T>(
		url: string,
		data?: any,
		params?: any,
		headers?: any,
		config?: AxiosRequestConfig
	): Promise<T> {
		const res = await this.axiosInstance.request({ url, method: "POST", data, params, headers, ...config });
		return res.data;
	}

	public async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
		const res = await this.axiosInstance.put(url, data, config);
		return res.data;
	}

	public async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
		const res = await this.axiosInstance.delete(url, config);
		return res.data;
	}

	public cancel(message?: string): void {
		const CancelToken = axios.CancelToken;
		const source = CancelToken.source();
		source.cancel(message);
	}
}
